package host

import (
	"github.com/kataras/iris/context"
	"app/models"
	"app/controller/base"
	"until/urldata"
	"until/logger"
	"fmt"
	"app/modules/rpc/grpcpool"
	"app/service"
	"strings"
	"app/modules/rpc/client"
	"app/modules/rpc/proto"
	"until/validate"
)

func List(ctx context.Context){
	hostModel := new(models.Host)
	queryParams := parseQueryParams(ctx)
	hosts, err := hostModel.List(queryParams)
	if err != nil {
		logger.Error(err)
		ctx.JSON(urldata.RetFail("错误"))
		return

	}
	ctx.JSON(urldata.RetSuccess(hosts))
}

type HostForm struct {
	Id     int  `form:"id"`
	Name   string `form:"name"`
	Alias  string `form:"alias"`
	Port   int    `form:"port"`
	Remark string `form:"remark"`
}
// Store 保存、修改主机信息
func Store(ctx context.Context){
	host_form:=HostForm{}
	err:=ctx.ReadForm(&host_form)
	if err!=nil {
		ctx.JSON(urldata.RetFail("参数错误"))
		return
	}
	hostModel := new(models.Host)
	nameExist, err := hostModel.NameExists(host_form.Name, host_form.Id)
	if err != nil {
		ctx.JSON(urldata.RetFail("操作失败"))
		return
	}
	if nameExist {
		ctx.JSON(urldata.RetFail("主机存在"))
		return
	}
	hostModel.Name=strings.TrimSpace(host_form.Name)
	hostModel.Port=host_form.Port
	hostModel.Remark=strings.TrimSpace(host_form.Remark)
	hostModel.Alias=strings.TrimSpace(host_form.Alias)
	if  err:=validate.Validate.Var(hostModel.Name,"ip");err!=nil{
		ctx.JSON(urldata.RetFail("主机名需为有效IP"))
		return
	}
	isCreate := false
	oldHostModel := new(models.Host)
	if host_form.Id>0 {
		_,err=hostModel.UpdateBean(host_form.Id)
		has:= oldHostModel.Find(host_form.Id)
		if !has {
			ctx.JSON(urldata.RetFail("主机不存在"))
			return
		}
	}else {
		isCreate=true
		_,err=hostModel.Create()
	}
	if err != nil {
		ctx.JSON(urldata.RetFail("修改失败"))
		return
	}
	if !isCreate {
		oldAddr := fmt.Sprintf("%s:%d", oldHostModel.Name, oldHostModel.Port)
		newAddr := fmt.Sprintf("%s:%d", hostModel.Name, hostModel.Port)
		if oldAddr != newAddr {
			grpcpool.Pool.Release(oldAddr)
		}
		taskModel := new(models.Task)
		tasks, err := taskModel.ActiveListByHostId(host_form.Id)
		if err != nil {
			ctx.JSON(urldata.RetFail("刷新任务主机信息失败:"+err.Error()))
		}
		serviceTask := new(service.Task)
		serviceTask.BatchAdd(tasks)

	}
	ctx.JSON(urldata.RetSuccess("保存成功"))

}
func Del(ctx context.Context)  {
	id,err:=ctx.Params().GetInt("id")
	if err!=nil||id<=0 {
		ctx.JSON(urldata.RetFail("参数错误"))
		return
	}
	taskHostModel := new(models.TaskHost)
	exist, err := taskHostModel.HostIdExist(id)
	if err != nil {
		ctx.JSON(urldata.RetFail("操作失败"))
		return
	}
	if exist {
		ctx.JSON(urldata.RetFail("有任务引用此主机，不能删除"))
		return
	}
	hostModel := new(models.Host)
	has:= hostModel.Find(id)
	if !has {
		ctx.JSON(urldata.RetFail("主机不存在"))
		return
	}
	_, err = hostModel.Delete(id)
	if err != nil {
		ctx.JSON(urldata.RetFail("操作失败"))
		return
	}

	addr := fmt.Sprintf("%s:%d", hostModel.Name, hostModel.Port)
	grpcpool.Pool.Release(addr)
	ctx.JSON(urldata.RetSuccess("操作成功"))

}
func Ping(ctx context.Context) {
	id,err:=ctx.Params().GetInt("id")
	if err!=nil||id<=0 {
		ctx.JSON(urldata.RetFail("参数错误"))
		return
	}
	hostModel := new(models.Host)
	has := hostModel.Find(id)
	if !has {
		ctx.JSON(urldata.RetFail("主机不存在"))
		return
	}
	taskReq := &rpc.TaskRequest{}
	taskReq.Command = "echo hello"
	taskReq.Timeout = 10
	output, err := client.Exec(hostModel.Name, hostModel.Port, taskReq)
	if err != nil {
		ctx.JSON(urldata.RetFail("连接失败-"+err.Error()+" "+output))
		return
	}
	ctx.JSON(urldata.RetSuccess("成功"))
}

// 解析查询参数
func parseQueryParams(ctx context.Context) models.CommonMap {
	var params models.CommonMap = models.CommonMap{}
	params["Id"],_ = ctx.PostValueInt("id")
	params["Name"] = ctx.PostValueTrim("name")
	base.ParsePageAndPageSize(ctx, params)
	return params
}